<!DOCTYPE HTML>
<html>

<head>
	<link rel="bookmark"  type="image/x-icon"  href="/img/logo_miccall.png"/>
	<link rel="shortcut icon" href="/img/logo_miccall.png">
	
			    <title>
    Ame雨
    </title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="/amelin-ting/css/mic_main.css" />
    <link rel="stylesheet" href="/amelin-ting/css/dropdownMenu.css" />
    <meta name="keywords" content="Ame雨" />
    
    	<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
	 
    <noscript>
        <link rel="stylesheet" href="/amelin-ting/css/noscript.css" />
    </noscript>
    <style type="text/css">
        body:before {
          content: ' ';
          position: fixed;
          top: 0;
          background: url('/amelin-ting/img/bg.jpg') center 0 no-repeat;
          right: 0;
          bottom: 0;
          left: 0;
          background-size: cover; 
        }
    </style>

			    
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script async type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


    <script src="/amelin-ting/js/jquery.min.js"></script>
    <script src="/amelin-ting/js/jquery.scrollex.min.js"></script>
    <script src="/amelin-ting/js/jquery.scrolly.min.js"></script>
    <script src="/amelin-ting/js/skel.min.js"></script>
    <script src="/amelin-ting/js/util.js"></script>
    <script src="/amelin-ting/js/main.js"></script>
	
<meta name="generator" content="Hexo 5.4.0"></head>
    
		
<!-- Layouts -->



<!--  代码渲染  -->
<link rel="stylesheet" href="/css/prism_coy.css" />
<link rel="stylesheet" href="/css/typo.css" />
<!-- 文章页 -->
<body class="is-loading">
    <!-- Wrapper 外包 s-->
    <div id="wrapper" class="fade-in">
        <!-- Intro 头部显示 s -->
        <!-- Intro 头部显示 e -->
        <!-- Header 头部logo start -->
        <header id="header">
    <a href="/amelin-ting/" class="logo">Art Space</a>
</header>
        <!-- Nav 导航条 start -->
        <nav id="nav" class="special" >
            <ul class="menu links" >
			<!-- Homepage  主页  --> 
			<li >
	            <a href="/amelin-ting/" rel="nofollow">主页</a>
	        </li>
			<!-- categories_name  分类   --> 
	        
	        <li class="active">
	            <a href="#s1">分类</a>
	                    <ul class="submenu">
	                        <li>
	                        <a class="category-link" href="/amelin-ting/categories/Go/">Go</a></li><li><a class="category-link" href="/amelin-ting/categories/django/">django</a></li><li><a class="category-link" href="/amelin-ting/categories/drf/">drf</a></li><li><a class="category-link" href="/amelin-ting/categories/gin/">gin</a></li><li><a class="category-link" href="/amelin-ting/categories/go/">go</a></li><li><a class="category-link" href="/amelin-ting/categories/linux/">linux</a></li><li><a class="category-link" href="/amelin-ting/categories/mysql/">mysql</a></li><li><a class="category-link" href="/amelin-ting/categories/python/">python</a></li><li><a class="category-link" href="/amelin-ting/categories/%E5%86%85%E7%BD%91%E7%A9%BF%E9%80%8F/">内网穿透</a></li><li><a class="category-link" href="/amelin-ting/categories/%E5%89%8D%E7%AB%AF/">前端</a>
	                    </ul>
	        </li>
	        
	        <!-- archives  归档   --> 
	        
	        
		        <!-- Pages 自定义   -->
		        
		        <li>
		            <a href="/about/" title="简历">
		                简历
		            </a>
		        </li>
		        
		        <li>
		            <a href="/group/" title="团队">
		                团队
		            </a>
		        </li>
		        
		        <li>
		            <a href="/gallery/" title="图库">
		                图库
		            </a>
		        </li>
		        
		        <li>
		            <a href="/tag/" title="标签">
		                标签
		            </a>
		        </li>
		        


            </ul>
            <!-- icons 图标   -->
			<ul class="icons">
                    
                    <li>
                        <a title="github" href="https://github.com/miccall" target="_blank" rel="noopener">
                            <i class="icon fa fa-github"></i>
                        </a>
                    </li>
                    
                    <li>
                        <a title="500px" href="http://500px.com" target="_blank" rel="noopener">
                            <i class="icon fa fa-500px"></i>
                        </a>
                    </li>
                    
			</ul>
</nav>

        <div id="main" >
            <div class ="post_page_title_img" style="height: 25rem;background-image: url(https://img1.baidu.com/it/u=3788617063,3371352907&amp;fm=26&amp;fmt=auto);background-position: center; background-repeat:no-repeat; background-size:cover;-moz-background-size:cover;overflow:hidden;" >
                <a href="#" style="padding: 4rem 4rem 2rem 4rem ;"><h2 >djangoOrm</h2></a>
            </div>
            <!-- Post -->
            <div class="typo" style="padding: 3rem;">
                <h2 id="一、pycharm连接数据库-MySQL"><a href="#一、pycharm连接数据库-MySQL" class="headerlink" title="一、pycharm连接数据库(MySQL)"></a>一、pycharm连接数据库(MySQL)</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">三个位置查找数据库相关</span></span><br><span class="line"><span class="string">	右侧上方database</span></span><br><span class="line"><span class="string">	左下方database</span></span><br><span class="line"><span class="string">	配置里面的plugins插件搜索安装</span></span><br><span class="line"><span class="string">	</span></span><br><span class="line"><span class="string">	再没有卸载pycharm重新装	</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">pycharm可以充当很多款数据库软件的客户端</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">	需要提前创建好库</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h2 id="二、Django连接数据库-MySQL"><a href="#二、Django连接数据库-MySQL" class="headerlink" title="二、Django连接数据库(MySQL)"></a>二、Django连接数据库(MySQL)</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 默认用的是sqlite3</span></span><br><span class="line">DATABASES = &#123;</span><br><span class="line">    <span class="string">&#x27;default&#x27;</span>: &#123;</span><br><span class="line">        <span class="string">&#x27;ENGINE&#x27;</span>: <span class="string">&#x27;django.db.backends.sqlite3&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;NAME&#x27;</span>: os.path.join(BASE_DIR, <span class="string">&#x27;db.sqlite3&#x27;</span>),</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># django链接MySQL</span></span><br><span class="line">	<span class="number">1.</span>第一步配置文件中配置</span><br><span class="line">  	DATABASES = &#123;</span><br><span class="line">    <span class="string">&#x27;default&#x27;</span>: &#123;</span><br><span class="line">        <span class="string">&#x27;ENGINE&#x27;</span>: <span class="string">&#x27;django.db.backends.mysql&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;NAME&#x27;</span>: <span class="string">&#x27;day60&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;USER&#x27;</span>:<span class="string">&#x27;root&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;PASSWORD&#x27;</span>:<span class="string">&#x27;admin123&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;HOST&#x27;</span>:<span class="string">&#x27;127.0.0.1&#x27;</span>,</span><br><span class="line">        <span class="string">&#x27;PORT&#x27;</span>:<span class="number">3306</span>,</span><br><span class="line">        <span class="string">&#x27;CHARSET&#x27;</span>:<span class="string">&#x27;utf8&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">  <span class="number">2.</span>代码声明	</span><br><span class="line">  	django默认用的是mysqldb模块链接MySQL</span><br><span class="line">    但是该模块的兼容性不好 需要手动改为用pymysql链接</span><br><span class="line">    </span><br><span class="line">    你需要告诉django不要用默认的mysqldb还是用pymysql</span><br><span class="line">    <span class="comment"># 在项目名下的init或者任意的应用名下的init文件中书写以下代码都可以</span></span><br><span class="line">    <span class="keyword">import</span> pymysql</span><br><span class="line">		pymysql.install_as_MySQLdb()</span><br></pre></td></tr></table></figure>

<h2 id="三、Django-orm"><a href="#三、Django-orm" class="headerlink" title="三、Django  orm"></a>三、Django  orm</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">ORM. 对象关系映射</span></span><br><span class="line"><span class="string">作用:能够让一个不用sql语句的小白也能够通过python 面向对象的代码简单快捷的操作数据库</span></span><br><span class="line"><span class="string">不足之处:封装程度太高 有时候sql语句的效率偏低 需要你自己写SQL语句</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">类											表</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">对象									记录</span></span><br><span class="line"><span class="string">	</span></span><br><span class="line"><span class="string">对象属性							记录某个字段对应的值</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">应用下面的models.py文件</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="number">1</span> 先去models.py中书写一个类</span><br><span class="line">	<span class="class"><span class="keyword">class</span> <span class="title">User</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">    <span class="comment"># id int primary_key auto_increment</span></span><br><span class="line">    <span class="built_in">id</span> = models.AutoField(primary_key=<span class="literal">True</span>)</span><br><span class="line">    <span class="comment"># username varchar(32)</span></span><br><span class="line">    username = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    <span class="comment"># password int</span></span><br><span class="line">    password = models.IntegerField()</span><br><span class="line"></span><br><span class="line">*************************<span class="number">2</span> 数据库迁移命令*************************</span><br><span class="line">python3 manage.py makemigrations 将操作记录记录到小本本上(migrations文件夹)</span><br><span class="line"></span><br><span class="line">python3 manage.py migrate  将操作真正的同步到数据库中</span><br><span class="line"><span class="comment"># 只要你修改了models.py中跟数据库相关的代码 就必须重新执行上述的两条命令</span></span><br><span class="line">******************************************************************</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">    <span class="comment"># id int primary_key auto_increment</span></span><br><span class="line">    <span class="built_in">id</span> = models.AutoField(primary_key=<span class="literal">True</span>,verbose_name=<span class="string">&#x27;主键&#x27;</span>)</span><br><span class="line">    <span class="comment"># username varchar(32)</span></span><br><span class="line">    username = models.CharField(max_length=<span class="number">32</span>,verbose_name=<span class="string">&#x27;用户名&#x27;</span>)</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    CharField必须要指定max_length参数 不指定会直接报错</span></span><br><span class="line"><span class="string">    verbose_name该参数是所有字段都有的 就是用来对字段的解释</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="comment"># password int</span></span><br><span class="line">    password = models.IntegerField(verbose_name=<span class="string">&#x27;密码&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">    <span class="comment"># 由于一张表中必须要有一个主键字段 并且一般情况下都叫id字段</span></span><br><span class="line">    <span class="comment"># 所以orm当你不定义主键字段的时候 orm会自动帮你创建一个名为id主键字段</span></span><br><span class="line">    <span class="comment"># 也就意味着 后续我们在创建模型表的时候如果主键字段名没有额外的叫法 那么主键字段可以省略不写</span></span><br><span class="line">    <span class="comment"># username varchar(32)</span></span><br><span class="line">    username = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    <span class="comment"># password int</span></span><br><span class="line">    password = models.IntegerField()</span><br></pre></td></tr></table></figure>

<h2 id="四、字段的增删改查"><a href="#四、字段的增删改查" class="headerlink" title="四、字段的增删改查"></a>四、字段的增删改查</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 字段的增加</span></span><br><span class="line">    <span class="number">1.</span>可以在终端内直接给出默认值</span><br><span class="line">    <span class="number">2.</span>该字段可以为空</span><br><span class="line">        info = models.CharField(max_length=<span class="number">32</span>,verbose_name=<span class="string">&#x27;个人简介&#x27;</span>,null=<span class="literal">True</span>)</span><br><span class="line">    <span class="number">3.</span>直接给字段设置默认值</span><br><span class="line">        hobby = models.CharField(max_length=<span class="number">32</span>,verbose_name=<span class="string">&#x27;兴趣爱好&#x27;</span>,default=<span class="string">&#x27;study&#x27;</span>)</span><br><span class="line"> </span><br><span class="line"><span class="comment"># 字段的修改</span></span><br><span class="line">	直接修改代码然后执行数据库迁移的两条命令即可！</span><br><span class="line"></span><br><span class="line"><span class="comment"># 字段的删</span></span><br><span class="line">	直接注释对应的字段然后执行数据库迁移的两条命令即可！</span><br><span class="line">  执行完毕之后字段对应的数据也都没有了</span><br><span class="line">  </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">在操作models.py的时候一定要细心</span></span><br><span class="line"><span class="string">	千万不要注释一些字段</span></span><br><span class="line"><span class="string">	执行迁移命令之前最好先检查一下自己写的代码</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 个人建议:当你离开你的计算机之后一定要锁屏</span></span><br></pre></td></tr></table></figure>

<h2 id="五、数据的增删改查"><a href="#五、数据的增删改查" class="headerlink" title="五、数据的增删改查"></a>五、数据的增删改查</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 只会介绍一点点 后面会详细的介绍</span></span><br><span class="line"></span><br><span class="line"><span class="number">1.</span>查</span><br><span class="line">res = models.User.objects.<span class="built_in">filter</span>(username=username)</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">返回值你先看成是列表套数据对象的格式</span></span><br><span class="line"><span class="string">它也支持索引取值 切片操作 但是不支持负数索引</span></span><br><span class="line"><span class="string">它也不推荐你使用索引的方式取值</span></span><br><span class="line"><span class="string">user_obj = models.User.objects.filter(username=username).first()</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="built_in">filter</span>括号内可以携带多个参数 参数与参数之间默认是<span class="keyword">and</span>关系</span><br><span class="line">你可以把<span class="built_in">filter</span>联想成where记忆</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>增</span><br><span class="line"><span class="keyword">from</span> app01 <span class="keyword">import</span> models</span><br><span class="line">res = models.User.objects.create(username=username,password=password)</span><br><span class="line"><span class="comment"># 返回值就是当前被创建的对象本身</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 第二种增加</span></span><br><span class="line">user_obj = models.User(username=username,password=password)</span><br><span class="line">user_obj.save()  <span class="comment"># 保存数据</span></span><br><span class="line"></span><br><span class="line"><span class="number">3.</span> 先讲数据库中的数据全部展示到前端 然后给每一个数据两个按钮 一个编辑一个删除</span><br><span class="line"></span><br><span class="line"><span class="number">3.1</span> 查看</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">userlist</span>(<span class="params">request</span>):</span></span><br><span class="line">    <span class="comment"># 查询出用户表里面所有的数据</span></span><br><span class="line">    <span class="comment"># 方式1</span></span><br><span class="line">    data = models.User.objects.<span class="built_in">filter</span>()</span><br><span class="line">    <span class="built_in">print</span>(data)</span><br><span class="line">    <span class="comment"># 方式2</span></span><br><span class="line">    user_queryset = models.User.objects.<span class="built_in">all</span>()</span><br><span class="line">    <span class="keyword">return</span> render(request,<span class="string">&#x27;userlist.html&#x27;</span>,&#123;<span class="string">&#x27;user_queryset&#x27;</span>:user_queryset&#125;)</span><br><span class="line">    <span class="keyword">return</span> render(request,<span class="string">&#x27;userlist.html&#x27;</span>,<span class="built_in">locals</span>())</span><br><span class="line"></span><br><span class="line"><span class="number">3.2</span> 编辑功能</span><br><span class="line">	<span class="comment"># 点击编辑按钮朝后端发送编辑数据的请求</span></span><br><span class="line">  <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">  如何告诉后端用户想要编辑哪条数据?</span></span><br><span class="line"><span class="string">  	将编辑按钮所在的那一行数据的主键值发送给后端</span></span><br><span class="line"><span class="string">  	利用url问号后面携带参数的方式</span></span><br><span class="line"><span class="string">  	</span></span><br><span class="line"><span class="string">  	&#123;% for user_obj in user_queryset %&#125;</span></span><br><span class="line"><span class="string">                        &lt;tr&gt;</span></span><br><span class="line"><span class="string">                            &lt;td&gt;&#123;&#123; user_obj.id &#125;&#125;&lt;/td&gt;</span></span><br><span class="line"><span class="string">                            &lt;td&gt;&#123;&#123; user_obj.username &#125;&#125;&lt;/td&gt;</span></span><br><span class="line"><span class="string">                            &lt;td&gt;&#123;&#123; user_obj.password &#125;&#125;&lt;/td&gt;</span></span><br><span class="line"><span class="string">                            &lt;td&gt;</span></span><br><span class="line"><span class="string">                                &lt;a href=&quot;/edit_user/?user_id=&#123;&#123; user_obj.id &#125;&#125;&quot; class=&quot;btn btn-primary btn-xs&quot;&gt;编辑&lt;/a&gt;</span></span><br><span class="line"><span class="string">                                &lt;a href=&quot;&quot; class=&quot;btn btn-danger btn-xs&quot;&gt;删除&lt;/a&gt;</span></span><br><span class="line"><span class="string">                            &lt;/td&gt;</span></span><br><span class="line"><span class="string">                        &lt;/tr&gt;</span></span><br><span class="line"><span class="string">                    &#123;% endfor %&#125;</span></span><br><span class="line"><span class="string">  &quot;&quot;&quot;</span></span><br><span class="line">  <span class="comment"># 后端查询出用户想要编辑的数据对象 展示到前端页面供用户查看和编辑</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">edit_user</span>(<span class="params">request</span>):</span></span><br><span class="line">    <span class="comment"># 获取url问号后面的参数</span></span><br><span class="line">    edit_id = request.GET.get(<span class="string">&#x27;user_id&#x27;</span>)</span><br><span class="line">    <span class="comment"># 查询当前用户想要编辑的数据对象</span></span><br><span class="line">    edit_obj = models.User.objects.<span class="built_in">filter</span>(<span class="built_in">id</span>=edit_id).first()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">&quot;POST&quot;</span>:</span><br><span class="line">        username = request.POST.get(<span class="string">&#x27;username&#x27;</span>)</span><br><span class="line">        password = request.POST.get(<span class="string">&#x27;password&#x27;</span>)</span><br><span class="line">        <span class="comment"># 去数据库中修改对应的数据内容</span></span><br><span class="line">        <span class="comment"># 修改数据方式1</span></span><br><span class="line">        models.User.objects.<span class="built_in">filter</span>(<span class="built_in">id</span>=edit_id).update(username=username,password=password)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">            将filter查询出来的列表中所有的对象全部更新            批量更新操作</span></span><br><span class="line"><span class="string">            只修改被修改的字段</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 修改数据方式2</span></span><br><span class="line">        edit_obj.username = username</span><br><span class="line">        edit_obj.password= password</span><br><span class="line">        edit_obj.save()</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">            上述方法当字段特别多的时候效率会非常的低</span></span><br><span class="line"><span class="string">            从头到尾将数据的所有字段全部更新一边 无论该字段是否被修改</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment"># 跳转到数据的展示页面</span></span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">&#x27;/userlist/&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 将数据对象展示到页面上</span></span><br><span class="line">    <span class="keyword">return</span> render(request,<span class="string">&#x27;edit_user.html&#x27;</span>,<span class="built_in">locals</span>())</span><br><span class="line"></span><br><span class="line"><span class="number">3.3</span> 删除功能</span><br><span class="line">	<span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">	跟编辑功能逻辑类似</span></span><br><span class="line"><span class="string">	def delete_user(request):</span></span><br><span class="line"><span class="string">    # 获取用户想要删除的数据id值</span></span><br><span class="line"><span class="string">    delete_id = request.GET.get(&#x27;user_id&#x27;)</span></span><br><span class="line"><span class="string">    # 直接去数据库中找到对应的数据删除即可</span></span><br><span class="line"><span class="string">    models.User.objects.filter(id=delete_id).delete()</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">        批量删除</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    # 跳转到展示页面</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    return redirect(&#x27;/userlist/&#x27;)	</span></span><br><span class="line"><span class="string">	</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span></span><br><span class="line"><span class="comment"># 真正的删除功能应该需要二次确认 我们这里先不做后面会讲</span></span><br><span class="line"><span class="comment"># 删除数据内部其实并不是真正的删除 我们会给数据添加一个标识字段用来表示当前数据是否被删除了，如果数据被删了仅仅只是讲字段修改一个状态</span></span><br><span class="line">	username password	is_delete</span><br><span class="line">  jason			<span class="number">123</span>				<span class="number">0</span></span><br><span class="line">  egon			<span class="number">123</span>				<span class="number">1</span></span><br></pre></td></tr></table></figure>

<h2 id="六、ORM的表连接"><a href="#六、ORM的表连接" class="headerlink" title="六、ORM的表连接"></a>六、ORM的表连接</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 表与表之间的关系</span><br><span class="line">	一对多   多对多   一对一   没有关系</span><br><span class="line">	判断表关系的方法:换位思考</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    图书表   出版社表   作者表   作者详情表</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    图书和出版社是一对多的关系 外键字段建在多的那一方 book</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    图书和作者是多对多的关系 需要创建第三张表来专门存储</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    作者与作者详情表是一对一</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="number">2.</span> 代码演示并解读</span><br><span class="line">    <span class="keyword">from</span> django.db <span class="keyword">import</span> models</span><br><span class="line"></span><br><span class="line">    <span class="comment"># Create your models here.</span></span><br><span class="line"></span><br><span class="line">    <span class="string">&quot;&quot;&quot;这边推荐先写完正常的数据字段 在写外键字段&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        title = models.CharField(max_length=<span class="number">16</span>)</span><br><span class="line">        <span class="comment"># DecimalField这个是小数   后面的第一个参数是可以有8个小数，第二个参数是保留2个小数</span></span><br><span class="line">        price = models.DecimalField(max_digits=<span class="number">8</span>, decimal_places=<span class="number">2</span>)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        图书跟出版社是一对多的关系 然后外键建在多的这一方</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        publish = models.ForeignKey(to=<span class="string">&#x27;Publish&#x27;</span>)  <span class="comment"># to_field 默认就是与出版社表的主键字段做外键关联</span></span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        如果字段对应的是ForeignKey 那么会orm会自动在字段的后面加_id</span></span><br><span class="line"><span class="string">        如果我们在命名变量名的时候如果加上_id </span></span><br><span class="line"><span class="string">        orm还是会给你加上_id  就会变成publish_id_id</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        接下来我们来分析图书跟作者的关系</span></span><br><span class="line"><span class="string">        这很明显是多对多所以我们对这两个表进行操作</span></span><br><span class="line"><span class="string">        外键建在哪一方都可以 建议是在用的频率很多的一方</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        author = models.ManyToManyField(to=<span class="string">&#x27;Author&#x27;</span>)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        author是个虚拟字段 主要是告诉orm 这两张表是多对多的关系</span></span><br><span class="line"><span class="string">        然后让orm去创建第三个表</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Publish</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        name = models.CharField(max_length=<span class="number">16</span>)</span><br><span class="line">        addr = models.CharField(max_length=<span class="number">16</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Author</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">        age = models.IntegerField()</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        然后我们再来看看一对一的关系把 外键也是随便建 但是推荐建在查询率较高的的表</span></span><br><span class="line"><span class="string">        作者与作者详情的关系</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        author_detail = models.OneToOneField(to=<span class="string">&#x27;AuthorDetail&#x27;</span>)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        OneToOneField也会自动给字段加_id后缀</span></span><br><span class="line"><span class="string">        所以你也不要自作聪明的自己加_id</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">AuthorDetail</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        phone = models.BigIntegerField()  <span class="comment"># 或者直接字符类型</span></span><br><span class="line">        addr = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">        </span><br><span class="line"><span class="number">3.</span> 再次总结</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        orm中如何定义三种关系</span></span><br><span class="line"><span class="string">            publish = models.ForeignKey(to=&#x27;Publish&#x27;)  # 默认就是与出版社表的主键字段做外键关联</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">            authors = models.ManyToManyField(to=&#x27;Author&#x27;)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">            author_detail = models.OneToOneField(to=&#x27;AuthorDetail&#x27;)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">            ForeignKey</span></span><br><span class="line"><span class="string">            OneToOneField</span></span><br><span class="line"><span class="string">                会自动在字段后面加_id后缀</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 在django1.X版本中外键默认都是级联更新删除的</span></span><br><span class="line">    <span class="comment"># 多对多的表关系可以有好几种创建方式 这里暂且先介绍一种</span></span><br><span class="line">    <span class="comment"># 针对外键字段里面的其他参数 暂时不要考虑 如果感兴趣自己可以百度试试看</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="七、测试脚本"><a href="#七、测试脚本" class="headerlink" title="七、测试脚本"></a>七、测试脚本</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">当你只是想测试django中的某一个py文件内容 那么你可以不用书写前后端交互的形式</span></span><br><span class="line"><span class="string">而是直接写一个测试脚本即可</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">脚本代码无论是写在应用下的tests.py还是自己单独开设py文件都可以</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="comment"># 测试环境的准备 去manage.py中拷贝前四行代码 然后自己写两行</span></span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    os.environ.setdefault(<span class="string">&quot;DJANGO_SETTINGS_MODULE&quot;</span>, <span class="string">&quot;day64.settings&quot;</span>)</span><br><span class="line">    <span class="keyword">import</span> django</span><br><span class="line">    django.setup()</span><br><span class="line">    <span class="comment"># 在这个代码块的下面就可以测试django里面的单个py文件了</span></span><br></pre></td></tr></table></figure>

<h2 id="八、单表操作"><a href="#八、单表操作" class="headerlink" title="八、单表操作"></a>八、单表操作</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;Django自带的sqlite3数据库对日期格式不敏感 容易出错 所以还是得MySQL 永远的神&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    os.environ.setdefault(<span class="string">&quot;DJANGO_SETTINGS_MODULE&quot;</span>, <span class="string">&quot;DjangoOrm1.settings&quot;</span>)</span><br><span class="line">    <span class="keyword">import</span> django</span><br><span class="line">    django.setup()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">from</span> app01 <span class="keyword">import</span> models</span><br><span class="line"><span class="comment"># 增</span></span><br><span class="line">    models.User.objects.create(name=<span class="string">&#x27;Ame&#x27;</span>, age=<span class="number">18</span>, register_time=<span class="string">&#x27;1999-07-28&#x27;</span>)</span><br><span class="line">    <span class="keyword">import</span> datetime</span><br><span class="line">    ctime = datetime.datetime.now()</span><br><span class="line">    user_obj = models.User(name=<span class="string">&#x27;Yuki&#x27;</span>, age=<span class="number">18</span>, register_time=ctime)</span><br><span class="line">    user_obj.save()</span><br><span class="line"><span class="comment"># 删</span></span><br><span class="line">    models.User.objects.<span class="built_in">filter</span>(pk=<span class="number">2</span>).delete()</span><br><span class="line">    user_obj = models.User.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).first()</span><br><span class="line">    user_obj.delete()</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    pk会自动查找到当前表的主键字段 指代的就是当前表的主键字段</span></span><br><span class="line"><span class="string">    用了pk之后 你就不需要指代当前表的主键字段到底叫什么了</span></span><br><span class="line"><span class="string">        uid</span></span><br><span class="line"><span class="string">        pid</span></span><br><span class="line"><span class="string">        sid</span></span><br><span class="line"><span class="string">        ...</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    user_obj = models.User.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).first()</span><br><span class="line">    user_obj.delete()</span><br><span class="line"><span class="comment"># 改</span></span><br><span class="line">    models.User.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).update(name=<span class="string">&#x27;Yuki&#x27;</span>)</span><br><span class="line">    user_obj = models.User.objects.get(pk=<span class="number">1</span>)</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    get 方法返回的值其实就是数据的对象，但是我们不用他</span></span><br><span class="line"><span class="string">    因为假如数据不存在 就会报错 这个很鸡肋</span></span><br><span class="line"><span class="string">    所以我们还是会用filter</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    user_obj.name = <span class="string">&#x27;egonPPP&#x27;</span></span><br><span class="line">    user_obj.save()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="1、必知必会十三条"><a href="#1、必知必会十三条" class="headerlink" title="1、必知必会十三条"></a>1、必知必会十三条</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 单表操作必知必会<span class="number">13</span>条(其实还有很多)</span><br><span class="line">    <span class="number">1.1</span> <span class="built_in">all</span>() </span><br><span class="line">    	查看所有数据</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.2</span> <span class="built_in">filter</span>()</span><br><span class="line">    	带有过滤条件的查询</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.3</span> get() </span><br><span class="line">    	返回一个数据对象 但是数据不存在会报错</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.4</span> first()</span><br><span class="line">    	拿queryset里面第一个元素</span><br><span class="line">        res = models.User.objacts.<span class="built_in">all</span>().first()</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.5</span> last() </span><br><span class="line">    	拿queryset里面最后一个元素</span><br><span class="line">        res = models.User.objacts.<span class="built_in">all</span>().last()</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.6</span> values() </span><br><span class="line">   		可以指定获取的数据字段  select name,age <span class="keyword">from</span> ...     列表套字典</span><br><span class="line">   		res = models.User.objects.values(<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;age&#x27;</span>)  </span><br><span class="line">   		<span class="comment"># &lt;QuerySet [&#123;&#x27;name&#x27;: &#x27;jason&#x27;, &#x27;age&#x27;: 18&#125;, &#123;&#x27;name&#x27;: &#x27;egonPPP&#x27;, &#x27;age&#x27;: 84&#125;]&gt;</span></span><br><span class="line">        </span><br><span class="line">    <span class="number">1.7</span> values_list()</span><br><span class="line">    	跟values差不多，但是可以看做列表套元组</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.8</span> distinct()</span><br><span class="line">    	res = models.User.objects.values(<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;age&#x27;</span>).distinct()</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        去重一定要是一模一样的数据</span></span><br><span class="line"><span class="string">        如果带有主键那么肯定不一样 你在往后的查询中一定不要忽略主键</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        </span><br><span class="line">    <span class="number">1.9</span> order_by</span><br><span class="line">    	models.User.objects.order_by(<span class="string">&#x27;age&#x27;</span>)  <span class="comment"># 升序</span></span><br><span class="line">        models.User.<span class="built_in">object</span>.order_by(<span class="string">&#x27;-age&#x27;</span>)  <span class="comment"># 降序</span></span><br><span class="line">        </span><br><span class="line">    <span class="number">1.10</span> reverse()</span><br><span class="line">    	反转的前提是 数据已经排过序了  order_by()</span><br><span class="line">      	res = models.User.objects.<span class="built_in">all</span>()</span><br><span class="line">       	res1 = models.User.objects.order_by(<span class="string">&#x27;age&#x27;</span>).reverse()</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.11</span> count()</span><br><span class="line">     	统计当前数据的个数</span><br><span class="line">    	res = models.User.objects.count()</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.12</span> exclude()</span><br><span class="line">        排除在外</span><br><span class="line">        res = models.User.objects.exclude(name=<span class="string">&#x27;jason&#x27;</span>)</span><br><span class="line">        </span><br><span class="line">    <span class="number">1.13</span> exists()</span><br><span class="line">        基本用不到因为数据本身就自带布尔值  返回的是布尔值</span><br><span class="line">        res = models.User.objects.<span class="built_in">filter</span>(pk=<span class="number">10</span>).exists()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="2、查看内部sql语句方法"><a href="#2、查看内部sql语句方法" class="headerlink" title="2、查看内部sql语句方法"></a>2、查看内部sql语句方法</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 方式1</span></span><br><span class="line">res = models.User.objects.values_list(<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;age&#x27;</span>)  <span class="comment"># &lt;QuerySet [(&#x27;jason&#x27;, 18), (&#x27;egonPPP&#x27;, 84)]&gt;</span></span><br><span class="line"><span class="built_in">print</span>(res.query)</span><br><span class="line">queryset对象才能够点击query查看内部的sql语句</span><br><span class="line"></span><br><span class="line"><span class="comment"># 方式2:所有的sql语句都能查看</span></span><br><span class="line"><span class="comment"># 去配置文件中配置一下即可</span></span><br><span class="line">LOGGING = &#123;</span><br><span class="line">    <span class="string">&#x27;version&#x27;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="string">&#x27;disable_existing_loggers&#x27;</span>: <span class="literal">False</span>,</span><br><span class="line">    <span class="string">&#x27;handlers&#x27;</span>: &#123;</span><br><span class="line">        <span class="string">&#x27;console&#x27;</span>:&#123;</span><br><span class="line">            <span class="string">&#x27;level&#x27;</span>:<span class="string">&#x27;DEBUG&#x27;</span>,</span><br><span class="line">            <span class="string">&#x27;class&#x27;</span>:<span class="string">&#x27;logging.StreamHandler&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">&#x27;loggers&#x27;</span>: &#123;</span><br><span class="line">        <span class="string">&#x27;django.db.backends&#x27;</span>: &#123;</span><br><span class="line">            <span class="string">&#x27;handlers&#x27;</span>: [<span class="string">&#x27;console&#x27;</span>],</span><br><span class="line">            <span class="string">&#x27;propagate&#x27;</span>: <span class="literal">True</span>,</span><br><span class="line">            <span class="string">&#x27;level&#x27;</span>:<span class="string">&#x27;DEBUG&#x27;</span>,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3、神奇的双下划线查询"><a href="#3、神奇的双下划线查询" class="headerlink" title="3、神奇的双下划线查询"></a>3、神奇的双下划线查询</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 年龄大于33</span></span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(age__gt=<span class="number">33</span>)</span><br><span class="line">    <span class="built_in">print</span>(res)</span><br><span class="line"><span class="comment"># 年龄小于33</span></span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(age__lt=<span class="number">33</span>)</span><br><span class="line">    <span class="built_in">print</span>(res)</span><br><span class="line"><span class="comment"># 大于等于</span></span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(age__gte=<span class="number">33</span>)</span><br><span class="line"><span class="comment"># 小于等于</span></span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(age__lte=<span class="number">33</span>)</span><br><span class="line"><span class="comment"># 年龄是18 或者 44</span></span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(age__in=[<span class="number">18</span>, <span class="number">44</span>])</span><br><span class="line"><span class="comment"># 年龄在18-80之间 首尾都包括</span></span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(age__range=[<span class="number">18</span>, <span class="number">80</span>])</span><br><span class="line"><span class="comment"># 模糊查询 包括一个‘u’</span></span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(name__contains=<span class="string">&#x27;u&#x27;</span>)</span><br><span class="line">    <span class="comment"># 是否区分大小写  查询出名字里面含有p的数据  区分大小写</span></span><br><span class="line">        res = models.User.objects.<span class="built_in">filter</span>(name__contains=<span class="string">&#x27;p&#x27;</span>)</span><br><span class="line">        <span class="built_in">print</span>(res)</span><br><span class="line">    <span class="comment"># 忽略大小写</span></span><br><span class="line">        res = models.User.objects.<span class="built_in">filter</span>(name__icontains=<span class="string">&#x27;p&#x27;</span>)</span><br><span class="line">        <span class="built_in">print</span>(res)</span><br><span class="line"><span class="comment"># 首字母开头查询</span></span><br><span class="line">	res = models.User.objects.<span class="built_in">filter</span>(name__startswith=<span class="string">&#x27;j&#x27;</span>)</span><br><span class="line"><span class="comment"># 尾字母查询</span></span><br><span class="line">    res1 = models.User.objects.<span class="built_in">filter</span>(name__endswith=<span class="string">&#x27;j&#x27;</span>)</span><br><span class="line"><span class="comment"># 查询出注册时间是 2020 1月</span></span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(register_time__month=<span class="string">&#x27;1&#x27;</span>)</span><br><span class="line">    res = models.User.objects.<span class="built_in">filter</span>(register_time__year=<span class="string">&#x27;2020&#x27;</span>)</span><br></pre></td></tr></table></figure>

<h3 id="4、外键的增删改查"><a href="#4、外键的增删改查" class="headerlink" title="4、外键的增删改查"></a>4、外键的增删改查</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 一对多(一对一也是一样的)</span><br><span class="line">    <span class="comment"># 增 第一种方法</span></span><br><span class="line">        models.Book.objects.create(title=<span class="string">&#x27;python&#x27;</span>, price=<span class="number">300.33</span>, publish_id=<span class="number">1</span>)</span><br><span class="line">        models.Book.objects.create(title=<span class="string">&#x27;jpm&#x27;</span>, price=<span class="number">1111.33</span>, publish_id=<span class="number">1</span>)</span><br><span class="line">        models.Book.objects.create(title=<span class="string">&#x27;my_song&#x27;</span>, price=<span class="number">666.33</span>, publish_id=<span class="number">2</span>)</span><br><span class="line">    <span class="comment"># 第二种方法</span></span><br><span class="line">        publish_obj = models.Publish.objects.<span class="built_in">filter</span>(pk=<span class="number">2</span>).first()</span><br><span class="line">        models.Book.objects.create(title=<span class="string">&#x27;linux&#x27;</span>, price=<span class="number">233.33</span>, publish=publish_obj)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        publish_id 可以直接传ID过去</span></span><br><span class="line"><span class="string">        publish 这个是虚拟字段 可以直接传对象过去</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">    <span class="comment"># 删除</span></span><br><span class="line">        models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">3</span>).delete()</span><br><span class="line">    <span class="comment"># 修改</span></span><br><span class="line">        models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">4</span>).update(publish_id=<span class="number">1</span>)</span><br><span class="line">        publish_obj = models.Publish.objects.<span class="built_in">filter</span>(pk=<span class="number">2</span>).first()</span><br><span class="line">        models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).update(publish=publish_obj)</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span> 多对多</span><br><span class="line">	<span class="string">&quot;&quot;&quot;在这里我们有一个疑问 多对多的第三张表是orm创建的呀，我们怎么去操作他呢&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 如何给书籍添加作者？</span></span><br><span class="line">        book_obj = models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).first()</span><br><span class="line">        <span class="built_in">print</span>(book_obj.authors)  <span class="comment"># 就类似于你已经到了第三张关系表了</span></span><br><span class="line">        book_obj.authors.add(<span class="number">1</span>)  <span class="comment"># 书籍id为1的书籍绑定一个主键为1 的作者</span></span><br><span class="line">        book_obj.authors.add(<span class="number">2</span>,<span class="number">3</span>)</span><br><span class="line"></span><br><span class="line">        author_obj = models.Author.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).first()</span><br><span class="line">        author_obj1 = models.Author.objects.<span class="built_in">filter</span>(pk=<span class="number">2</span>).first()</span><br><span class="line">        author_obj2 = models.Author.objects.<span class="built_in">filter</span>(pk=<span class="number">3</span>).first()</span><br><span class="line">        book_obj.authors.add(author_obj)</span><br><span class="line">        book_obj.authors.add(author_obj1,author_obj2)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        add给第三张关系表添加数据</span></span><br><span class="line"><span class="string">            括号内既可以传数字也可以传对象 并且都支持多个</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 删</span></span><br><span class="line">        book_obj.authors.remove(<span class="number">2</span>)</span><br><span class="line">        book_obj.authors.remove(<span class="number">1</span>,<span class="number">3</span>)</span><br><span class="line"></span><br><span class="line">        author_obj = models.Author.objects.<span class="built_in">filter</span>(pk=<span class="number">2</span>).first()</span><br><span class="line">        author_obj1 = models.Author.objects.<span class="built_in">filter</span>(pk=<span class="number">3</span>).first()</span><br><span class="line">        book_obj.authors.remove(author_obj,author_obj1)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        remove</span></span><br><span class="line"><span class="string">            括号内既可以传数字也可以传对象 并且都支持多个</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 修改</span></span><br><span class="line">        book_obj.authors.<span class="built_in">set</span>([<span class="number">1</span>,<span class="number">2</span>])  <span class="comment"># 括号内必须给一个可迭代对象</span></span><br><span class="line">        book_obj.authors.<span class="built_in">set</span>([<span class="number">3</span>])  <span class="comment"># 括号内必须给一个可迭代对象</span></span><br><span class="line"></span><br><span class="line">        author_obj = models.Author.objects.<span class="built_in">filter</span>(pk=<span class="number">2</span>).first()</span><br><span class="line">        author_obj1 = models.Author.objects.<span class="built_in">filter</span>(pk=<span class="number">3</span>).first()</span><br><span class="line">        book_obj.authors.<span class="built_in">set</span>([author_obj,author_obj1])  <span class="comment"># 括号内必须给一个可迭代对象</span></span><br><span class="line"></span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        set</span></span><br><span class="line"><span class="string">            括号内必须传一个可迭代对象，该对象内既可以数字也可以对象 并且都支持多个</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 清空</span></span><br><span class="line">    <span class="comment"># 在第三张关系表中清空某个书籍与作者的绑定关系</span></span><br><span class="line">        book_obj.authors.clear()</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        clear</span></span><br><span class="line"><span class="string">            括号内不要加任何参数</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h2 id="九、多表查询"><a href="#九、多表查询" class="headerlink" title="九、多表查询"></a>九、多表查询</h2><h3 id="1、正向与反向"><a href="#1、正向与反向" class="headerlink" title="1、正向与反向"></a>1、正向与反向</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 正向</span></span><br><span class="line"><span class="comment"># 反向</span></span><br><span class="line">	外键字段在我手上那么，我查你就是正向</span><br><span class="line">  外键字段如果不在手上，我查你就是反向</span><br><span class="line">  </span><br><span class="line">  book &gt;&gt;&gt;外键字段在书那儿(正向)&gt;&gt;&gt; publish</span><br><span class="line">  publish	&gt;&gt;&gt;外键字段在书那儿(反向)&gt;&gt;&gt;book</span><br><span class="line">  </span><br><span class="line">  一对一和多对多正反向的判断也是如此</span><br><span class="line">  </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">正向查询按字段</span></span><br><span class="line"><span class="string">反向查询按表名小写</span></span><br><span class="line"><span class="string">				_set</span></span><br><span class="line"><span class="string">				...</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="2、子查询-基于对象的跨表查询"><a href="#2、子查询-基于对象的跨表查询" class="headerlink" title="2、子查询(基于对象的跨表查询)"></a>2、子查询(基于对象的跨表查询)</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 正向查询</span><br><span class="line">    <span class="comment"># 1.查询书籍主键为1的出版社  书&gt;&gt;&gt;&gt;&gt;&gt;出版社 外键在书 所以是正向查询</span></span><br><span class="line">        book_obj = models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).first()</span><br><span class="line">        res = book_obj.publish</span><br><span class="line">        <span class="built_in">print</span>(res)  <span class="comment"># 返回值为出版社的对象 所以我们就能直接调用方法来看</span></span><br><span class="line">        <span class="built_in">print</span>(res.name)</span><br><span class="line">    <span class="comment"># 2.查询书籍主键为2的作者   书&gt;&gt;&gt;&gt;&gt;作者  外键在书 所以是正向查询</span></span><br><span class="line">        book_obj = models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">2</span>).first()</span><br><span class="line">        res1 = book_obj.author.<span class="built_in">all</span>()</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        app01.Author.None 遇到输出结果是这个的时候就得加.all()</span></span><br><span class="line"><span class="string">        原因是因为一本书会对应多个作者</span></span><br><span class="line"><span class="string">        加了.all()就会返回 &lt;QuerySet [&lt;Author: Author object&gt;, &lt;Author: Author object&gt;]&gt;</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="built_in">print</span>(res1)  <span class="comment"># 返回值为作者的对象</span></span><br><span class="line">        <span class="built_in">print</span>(res1[<span class="number">0</span>].name)  <span class="comment"># 返回的是QuerySet类型，就得依靠索引来查</span></span><br><span class="line">    <span class="comment"># 3.查询作者yxx的电话号码  作者&gt;&gt;&gt;&gt;&gt;作者详情 外键在作者 所以是正向查询</span></span><br><span class="line">        author_obj = models.Author.objects.<span class="built_in">filter</span>(name=<span class="string">&#x27;yxx&#x27;</span>).first()</span><br><span class="line">        res2 = author_obj.author_detail</span><br><span class="line">        <span class="built_in">print</span>(res2)  <span class="comment"># 返回值为作者详情的对象</span></span><br><span class="line">        <span class="built_in">print</span>(res2.phone)</span><br><span class="line">        </span><br><span class="line"><span class="number">2.</span> 反向查询</span><br><span class="line">    <span class="comment"># 4.查询出版社是东方出版社出版的书  出版社&gt;&gt;&gt;&gt;&gt;书  出版社没有外键 所以是反向</span></span><br><span class="line">        publish_obj = models.Publish.objects.<span class="built_in">filter</span>(name=<span class="string">&#x27;东方&#x27;</span>).first()</span><br><span class="line">        res = publish_obj.book_set.<span class="built_in">all</span>()  <span class="comment"># 返回值为书的对象</span></span><br><span class="line">        <span class="built_in">print</span>(res)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 5.查询作者是yxx写过的书   作者&gt;&gt;&gt;&gt;书  作者没有外键 所以是反向</span></span><br><span class="line">        author_obj = models.Author.objects.<span class="built_in">filter</span>(name=<span class="string">&#x27;yxx&#x27;</span>).first()</span><br><span class="line">        res1 = author_obj.book_set.<span class="built_in">all</span>()</span><br><span class="line">        <span class="built_in">print</span>(res1)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 6.查询手机号是28的作者姓名</span></span><br><span class="line">        author_detail_obj = models.AuthorDetail.objects.<span class="built_in">filter</span>(phone=<span class="number">28</span>).first()</span><br><span class="line">        res = author_detail_obj.author</span><br><span class="line">        <span class="built_in">print</span>(res.name)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        基于对象 </span></span><br><span class="line"><span class="string">            反向查询的时候</span></span><br><span class="line"><span class="string">                当你的查询结果可以有多个的时候 就必须加_set.all()</span></span><br><span class="line"><span class="string">                当你的结果只有一个的时候 不需要加_set.all()</span></span><br><span class="line"><span class="string">            自己总结出 自己方便记忆的即可 每个人都可以不一样</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="number">3.</span>注意</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    在书写orm语句的时候跟写sql语句一样的</span></span><br><span class="line"><span class="string">    不要企图一次性将orm语句写完 如果比较复杂 就写一点看一点</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    正向什么时候需要加.all()</span></span><br><span class="line"><span class="string">        当你的结果可能有多个的时候就需要加.all()</span></span><br><span class="line"><span class="string">            如果是一个则直接拿到数据对象</span></span><br><span class="line"><span class="string">            book_obj.publish</span></span><br><span class="line"><span class="string">            book_obj.authors.all()</span></span><br><span class="line"><span class="string">            author_obj.author_detail</span></span><br><span class="line"><span class="string">     &quot;&quot;&quot;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="3、基于下划线的跨表查询"><a href="#3、基于下划线的跨表查询" class="headerlink" title="3、基于下划线的跨表查询"></a>3、基于下划线的跨表查询</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>查询yxx的手机号和作者姓名</span><br><span class="line">    <span class="comment"># 正向</span></span><br><span class="line">        res = models.Author.objects.<span class="built_in">filter</span>(name=<span class="string">&#x27;yxx&#x27;</span>).values(<span class="string">&#x27;author_detail__phone&#x27;</span>, <span class="string">&#x27;name&#x27;</span>)</span><br><span class="line">    <span class="comment"># 反向</span></span><br><span class="line">        res1 = models.AuthorDetail.objects.<span class="built_in">filter</span>(author__name=<span class="string">&#x27;yxx&#x27;</span>).values(<span class="string">&#x27;author__name&#x27;</span>, <span class="string">&#x27;phone&#x27;</span>)</span><br><span class="line">        <span class="built_in">print</span>(res1)</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>查询书籍主键为<span class="number">1</span>的出版社名称和书的名称</span><br><span class="line">    <span class="comment"># 正向</span></span><br><span class="line">    	res2 = models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).values(<span class="string">&#x27;publish__name&#x27;</span>, <span class="string">&#x27;title&#x27;</span>)</span><br><span class="line">    <span class="comment"># 反向</span></span><br><span class="line">        res3 = models.Publish.objects.<span class="built_in">filter</span>(book__id=<span class="number">1</span>).values(<span class="string">&#x27;name&#x27;</span>, <span class="string">&#x27;book__title&#x27;</span>)</span><br><span class="line">        <span class="built_in">print</span>(res2)</span><br><span class="line">        <span class="built_in">print</span>(res3)</span><br><span class="line"></span><br><span class="line"><span class="number">3.</span>查询书籍主键为<span class="number">1</span>的作者姓名</span><br><span class="line">    <span class="comment"># 正向</span></span><br><span class="line">    	res4 = models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).values(<span class="string">&#x27;author__name&#x27;</span>)</span><br><span class="line">    <span class="comment"># 反向</span></span><br><span class="line">        res5 = models.Author.objects.<span class="built_in">filter</span>(book__id=<span class="number">1</span>).values(<span class="string">&#x27;name&#x27;</span>)</span><br><span class="line">        <span class="built_in">print</span>(res4)</span><br><span class="line">        <span class="built_in">print</span>(res5)</span><br><span class="line"></span><br><span class="line"><span class="number">4.</span>查询书籍主键是<span class="number">1</span>的作者的手机号</span><br><span class="line">    <span class="comment"># 正向</span></span><br><span class="line">   		res6 = models.Book.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).values(<span class="string">&quot;author__author_detail__phone&quot;</span>)</span><br><span class="line">    <span class="comment"># 反向</span></span><br><span class="line">        res7 = models.Author.objects.<span class="built_in">filter</span>(book__id=<span class="number">1</span>).values(<span class="string">&#x27;author_detail__phone&#x27;</span>)</span><br><span class="line">        <span class="built_in">print</span>(res6)</span><br><span class="line">        <span class="built_in">print</span>(res7)</span><br><span class="line">        </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">你只要掌握了正反向的概念</span></span><br><span class="line"><span class="string">以及双下划线</span></span><br><span class="line"><span class="string">那么你就可以无限制的跨表</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h2 id="十、聚合查询"><a href="#十、聚合查询" class="headerlink" title="十、聚合查询"></a>十、聚合查询</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>什么是聚合查询</span><br><span class="line">	其实就是MySQL的聚合函数的使用查询</span><br><span class="line"></span><br><span class="line"><span class="number">2.</span> 代码演示</span><br><span class="line">	<span class="comment"># 聚合查询      aggregate</span></span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    聚合查询通常情况下都是配合分组一起使用的</span></span><br><span class="line"><span class="string">    只要是跟数据库相关的模块 </span></span><br><span class="line"><span class="string">        基本上都在django.db.models里面</span></span><br><span class="line"><span class="string">        如果上述没有那么应该在django.db里面</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">from</span> django.db.models <span class="keyword">import</span> Max,Min,Avg,Count,Sum</span><br><span class="line">    <span class="comment"># 1 所有书的平均价格</span></span><br><span class="line">    res = models.Book.objects.aggregate(Avg(<span class="string">&#x27;price&#x27;</span>))</span><br><span class="line">    <span class="built_in">print</span>(res)</span><br><span class="line">    <span class="comment"># 2.上述方法一次性使用</span></span><br><span class="line">    res1 = models.Book.objects.aggregate(Max(<span class="string">&#x27;price&#x27;</span>), Min(<span class="string">&#x27;price&#x27;</span>), Count(<span class="string">&#x27;title&#x27;</span>), Sum(<span class="string">&#x27;price&#x27;</span>))</span><br><span class="line">    <span class="built_in">print</span>(res1)</span><br></pre></td></tr></table></figure>

<h2 id="十一、分组查询"><a href="#十一、分组查询" class="headerlink" title="十一、分组查询"></a>十一、分组查询</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 分组查询  annotate</span></span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    MySQL分组查询都有哪些特点</span></span><br><span class="line"><span class="string">        分组之后默认只能获取到分组的依据 组内其他字段都无法直接获取了</span></span><br><span class="line"><span class="string">            严格模式</span></span><br><span class="line"><span class="string">                ONLY_FULL_GROUP_BY</span></span><br><span class="line"><span class="string">                </span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">from</span> django.db.models <span class="keyword">import</span> Max, Min, Avg, Count, Sum</span><br><span class="line"></span><br><span class="line"><span class="comment"># 1.统计每一本书的作者个数</span></span><br><span class="line">    res = models.Book.objects.annotate(author_num=(Count(<span class="string">&#x27;author&#x27;</span>))).values(<span class="string">&#x27;author_num&#x27;</span>)</span><br><span class="line">    res1 = models.Book.objects.annotate(author_num=Count(<span class="string">&#x27;author__id&#x27;</span>)).values(<span class="string">&#x27;title&#x27;</span>, <span class="string">&#x27;author_num&#x27;</span>)</span><br><span class="line">    <span class="built_in">print</span>(res, res1)</span><br><span class="line"><span class="comment"># 2.统计每个出版社卖的最便宜的书的价格</span></span><br><span class="line">    res2 = models.Publish.objects.annotate(min_price=(Min(<span class="string">&#x27;book__price&#x27;</span>))).values(<span class="string">&#x27;min_price&#x27;</span>)</span><br><span class="line">    <span class="built_in">print</span>(res2)</span><br><span class="line"><span class="comment"># 3.统计不止一个作者的图书</span></span><br><span class="line">    res3 = models.Book.objects.annotate(author_num=(Count(<span class="string">&#x27;author__id&#x27;</span>))).<span class="built_in">filter</span>(author_num__gt=<span class="number">1</span>).values(<span class="string">&#x27;title&#x27;</span>,</span><br><span class="line">                                                                                                      <span class="string">&#x27;author_num&#x27;</span>)</span><br><span class="line">    <span class="built_in">print</span>(res3)</span><br><span class="line"><span class="comment"># 4.查询每个作者出的书的总价格</span></span><br><span class="line">    res4 = models.Author.objects.annotate(price_sum=(Sum(<span class="string">&#x27;book__price&#x27;</span>))).values(<span class="string">&#x27;price_sum&#x27;</span>)</span><br><span class="line">    <span class="built_in">print</span>(res4)</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    如果我想按照指定的字段分组该如何处理呢？</span></span><br><span class="line"><span class="string">        models.Book.objects.values(&#x27;price&#x27;).annotate()</span></span><br><span class="line"><span class="string">    后续BBS作业会使用</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">    你们的机器上如果出现分组查询报错的情况</span></span><br><span class="line"><span class="string">        你需要修改数据库严格模式</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h2 id="十二、F查询"><a href="#十二、F查询" class="headerlink" title="十二、F查询"></a>十二、F查询</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 什么是F查询</span><br><span class="line">	能够帮助你直接获取到表中某个字段对应的数据</span><br><span class="line"><span class="number">2.</span> 代码演示</span><br><span class="line">	<span class="keyword">from</span> django.db.models <span class="keyword">import</span> F</span><br><span class="line">    <span class="comment"># 1.查询卖出数大于库存数的书籍</span></span><br><span class="line">    res = models.Book.objects.<span class="built_in">filter</span>(sale__gt=F(<span class="string">&#x27;inventory&#x27;</span>))</span><br><span class="line">    <span class="built_in">print</span>(res)</span><br><span class="line">    <span class="comment"># 2.将所有书籍的价格提升500块</span></span><br><span class="line">    models.Book.<span class="built_in">object</span>.update(F(<span class="string">&#x27;price&#x27;</span>) + <span class="number">500</span>)</span><br><span class="line">    <span class="comment"># 3.将所有书的名称后面加上爆款两个字</span></span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    在操作字符类型的数据的时候 F不能够直接做到字符串的拼接</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">from</span> django.db.models.functions <span class="keyword">import</span> concat</span><br><span class="line">    <span class="keyword">from</span> django.db.models <span class="keyword">import</span> values</span><br><span class="line">    models.Book.objects.update(title=Concat(F(<span class="string">&#x27;title&#x27;</span>), Value(<span class="string">&#x27;爆款&#x27;</span>)))</span><br><span class="line">    <span class="comment"># models.Book.objects.update(title=F(&#x27;title&#x27;) + &#x27;爆款&#x27;)  # 所有的名称会全部变成空白</span></span><br></pre></td></tr></table></figure>

<h2 id="十三、Q查询"><a href="#十三、Q查询" class="headerlink" title="十三、Q查询"></a>十三、Q查询</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 什么是Q查询</span><br><span class="line">	能变换fitler里面的与或非关系</span><br><span class="line">   </span><br><span class="line"><span class="number">2.</span> 代码演示</span><br><span class="line">	<span class="keyword">from</span> django.db.models <span class="keyword">import</span> Q</span><br><span class="line">    <span class="comment"># 1.查询卖出数大于100或者价格小于600的书籍</span></span><br><span class="line">   	res = models.Book.<span class="built_in">object</span>.<span class="built_in">filter</span>(sale__gt=<span class="number">100</span>, price__lt=<span class="number">600</span>)  <span class="comment"># filter 里面默认是and关系 直接改成or not可不行</span></span><br><span class="line">    res = models.Book.<span class="built_in">object</span>.fitler(Q(sale__gt=<span class="number">100</span>)|(price__lt=<span class="number">600</span>)  <span class="comment"># |是 or 关系</span></span><br><span class="line">    res = models.Book.<span class="built_in">object</span>.fitler(~(sale__gt=<span class="number">100</span>)|(price__lt=<span class="number">600</span>)  <span class="comment"># ~是 not 关系</span></span><br><span class="line">    <span class="comment"># Q的高级用法 能够将查询条件的左边也变成字符串格式</span></span><br><span class="line">    q = Q()</span><br><span class="line">    q.children.append((<span class="string">&#x27;maichu__gt&#x27;</span>,<span class="number">100</span>))</span><br><span class="line">    q.children.append((<span class="string">&#x27;price__lt&#x27;</span>,<span class="number">600</span>))</span><br><span class="line">    res = models.Book.<span class="built_in">object</span>.fitler(q)  <span class="comment"># 默认还是and关系 所以得加一句代码  q.connector = &#x27;or&#x27;</span></span><br><span class="line">    <span class="built_in">print</span>(q)</span><br><span class="line">    </span><br></pre></td></tr></table></figure>

<h2 id="十四、Django中开启事务"><a href="#十四、Django中开启事务" class="headerlink" title="十四、Django中开启事务"></a>十四、Django中开启事务</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">事务</span></span><br><span class="line"><span class="string">	ACID</span></span><br><span class="line"><span class="string">		原子性</span></span><br><span class="line"><span class="string">			不可分割的最小单位</span></span><br><span class="line"><span class="string">		一致性</span></span><br><span class="line"><span class="string">			跟原子性是相辅相成</span></span><br><span class="line"><span class="string">		隔离性</span></span><br><span class="line"><span class="string">			事务之间互相不干扰</span></span><br><span class="line"><span class="string">		持久性</span></span><br><span class="line"><span class="string">			事务一旦确认永久生效</span></span><br><span class="line"><span class="string">	</span></span><br><span class="line"><span class="string">	事务的回滚 </span></span><br><span class="line"><span class="string">		rollback</span></span><br><span class="line"><span class="string">	事务的确认</span></span><br><span class="line"><span class="string">		commit</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="comment"># 目前你只需要掌握Django中如何简单的开启事务</span></span><br><span class="line"><span class="comment"># 事务</span></span><br><span class="line">    <span class="keyword">from</span> django.db <span class="keyword">import</span> transaction</span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">with</span> transaction.atomic():</span><br><span class="line">            <span class="comment"># sql1</span></span><br><span class="line">            <span class="comment"># sql2</span></span><br><span class="line">            ...</span><br><span class="line">            <span class="comment"># 在with代码快内书写的所有orm操作都是属于同一个事务</span></span><br><span class="line">    <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">        <span class="built_in">print</span>(e)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;执行其他操作&#x27;</span>)</span><br></pre></td></tr></table></figure>

<h2 id="十五、orm常用字段-amp-参数"><a href="#十五、orm常用字段-amp-参数" class="headerlink" title="十五、orm常用字段&amp;参数"></a>十五、orm常用字段&amp;参数</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line">AutoField</span><br><span class="line">	主键字段 primary_key=<span class="literal">True</span></span><br><span class="line">  </span><br><span class="line">CharField				varchar</span><br><span class="line">	verbose_name	字段的注释</span><br><span class="line">  max_length		长度</span><br><span class="line">  </span><br><span class="line">IntegerField			<span class="built_in">int</span></span><br><span class="line">BigIntegerField		bigint</span><br><span class="line"></span><br><span class="line">DecimalField</span><br><span class="line">	max_digits=<span class="number">8</span></span><br><span class="line">  decimal_places=<span class="number">2</span></span><br><span class="line"></span><br><span class="line">EmailFiled				varchar(<span class="number">254</span>)</span><br><span class="line"></span><br><span class="line">DateField					date</span><br><span class="line">DateTimeField			datetime</span><br><span class="line">	auto_now:每次修改数据的时候都会自动更新当前时间</span><br><span class="line">  auto_now_add:只在创建数据的时候记录创建时间后续不会自动修改了</span><br><span class="line">    </span><br><span class="line">BooleanField(Field)				- 布尔值类型</span><br><span class="line">	该字段传布尔值(<span class="literal">False</span>/<span class="literal">True</span>) 	数据库里面存<span class="number">0</span>/<span class="number">1</span></span><br><span class="line"></span><br><span class="line">TextField(Field)					- 文本类型</span><br><span class="line">	该字段可以用来存大段内容(文章、博客...)  没有字数限制</span><br><span class="line">  后面的bbs作业 文章字段用的就是TextField</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">FileField(Field)					- 字符类型</span><br><span class="line">   upload_to = <span class="string">&quot;/data&quot;</span></span><br><span class="line">  给该字段传一个文件对象，会自动将文件保存到/data目录下然后将文件路径保存到数据库中</span><br><span class="line">  /data/a.txt</span><br><span class="line">  后面bbs作业也会涉及</span><br><span class="line"></span><br><span class="line"><span class="comment"># 更多字段</span></span><br><span class="line">直接参考博客:https://www.cnblogs.com/Dominic-Ji/p/<span class="number">9203990.</span>html</span><br><span class="line"></span><br><span class="line">    </span><br><span class="line"><span class="comment"># django除了给你提供了很多字段类型之外 还支持你自定义字段</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyCharField</span>(<span class="params">models.Field</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,max_length,*args,**kwargs</span>):</span></span><br><span class="line">        self.max_length = max_length</span><br><span class="line">        <span class="comment"># 调用父类的init方法</span></span><br><span class="line">        <span class="built_in">super</span>().__init__(max_length=max_length,*args,**kwargs)  <span class="comment"># 一定要是关键字的形式传入</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">db_type</span>(<span class="params">self, connection</span>):</span></span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        返回真正的数据类型及各种约束条件</span></span><br><span class="line"><span class="string">        :param connection:</span></span><br><span class="line"><span class="string">        :return:</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;char(%s)&#x27;</span>%self.max_length</span><br><span class="line"></span><br><span class="line"><span class="comment"># 自定义字段使用</span></span><br><span class="line">myfield = MyCharField(max_length=<span class="number">16</span>,null=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 外键字段及参数</span></span><br><span class="line">unique=<span class="literal">True</span></span><br><span class="line">	ForeignKey(unique=<span class="literal">True</span>)   ===			OneToOneField()</span><br><span class="line">  <span class="comment"># 你在用前面字段创建一对一 orm会有一个提示信息 orm推荐你使用后者但是前者也能用</span></span><br><span class="line">  </span><br><span class="line">db_index</span><br><span class="line">	如果db_index=<span class="literal">True</span> 则代表着为此字段设置索引</span><br><span class="line">  (复习索引是什么)</span><br><span class="line"></span><br><span class="line">to_field</span><br><span class="line">	设置要关联的表的字段  默认不写关联的就是另外一张的主键字段</span><br><span class="line"></span><br><span class="line">on_delete</span><br><span class="line">	当删除关联表中的数据时，当前表与其关联的行的行为。</span><br><span class="line">  <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">  django2.X及以上版本 需要你自己指定外键字段的级联更新级联删除</span></span><br><span class="line"><span class="string">  &quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h2 id="十六、数据库查询优化"><a href="#十六、数据库查询优化" class="headerlink" title="十六、数据库查询优化"></a>十六、数据库查询优化</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line">only与defer	</span><br><span class="line">select_related与prefetch_related</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">orm语句的特点:</span></span><br><span class="line"><span class="string">	惰性查询</span></span><br><span class="line"><span class="string">		如果你仅仅只是书写了orm语句 在后面根本没有用到该语句所查询出来的参数</span></span><br><span class="line"><span class="string">		那么orm会自动识别 直接不执行</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="comment"># only与defer</span></span><br><span class="line">    	res = models.Book.objects.<span class="built_in">all</span>()</span><br><span class="line">        <span class="built_in">print</span>(res)  <span class="comment"># 要用数据了才会走数据库</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 想要获取书籍表中所有数的名字</span></span><br><span class="line">        res = models.Book.objects.values(<span class="string">&#x27;title&#x27;</span>)</span><br><span class="line">        <span class="keyword">for</span> d <span class="keyword">in</span> res:</span><br><span class="line">            <span class="built_in">print</span>(d.get(<span class="string">&#x27;title&#x27;</span>))</span><br><span class="line">        <span class="comment"># 你给我实现获取到的是一个数据对象 然后点title就能够拿到书名 并且没有其他字段</span></span><br><span class="line">        res = models.Book.objects.only(<span class="string">&#x27;title&#x27;</span>)</span><br><span class="line">        res = models.Book.objects.<span class="built_in">all</span>()</span><br><span class="line">        <span class="built_in">print</span>(res)  <span class="comment"># &lt;QuerySet [&lt;Book: 三国演义爆款&gt;, &lt;Book: 红楼梦爆款&gt;, &lt;Book: 论语爆款&gt;, &lt;Book: 聊斋爆款&gt;, &lt;Book: 老子爆款&gt;]&gt;</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> res:</span><br><span class="line">            <span class="built_in">print</span>(i.title)  <span class="comment"># 点击only括号内的字段 不会走数据库</span></span><br><span class="line">            <span class="built_in">print</span>(i.price)  <span class="comment"># 点击only括号内没有的字段 会重新走数据库查询而all不需要走了</span></span><br><span class="line"></span><br><span class="line">        res = models.Book.objects.defer(<span class="string">&#x27;title&#x27;</span>)  <span class="comment"># 对象除了没有title属性之外其他的都有</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> res:</span><br><span class="line">            <span class="built_in">print</span>(i.price)</span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        defer与only刚好相反</span></span><br><span class="line"><span class="string">            defer括号内放的字段不在查询出来的对象里面 查询该字段需要重新走数据</span></span><br><span class="line"><span class="string">            而如果查询的是非括号内的字段 则不需要走数据库了</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">    </span><br><span class="line"></span><br><span class="line"><span class="comment"># select_related与prefetch_related</span></span><br><span class="line">    select_related与prefetch_related  跟跨表操作有关</span><br><span class="line">        res = models.Book.objects.<span class="built_in">all</span>()</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> res:</span><br><span class="line">            <span class="built_in">print</span>(i.publish.name)  <span class="comment"># 每循环一次就要走一次数据库查询</span></span><br><span class="line"></span><br><span class="line">        res = models.Book.objects.select_related(<span class="string">&#x27;authors&#x27;</span>)  <span class="comment"># INNER JOIN</span></span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        select_related内部直接先将book与publish连起来 然后一次性将大表里面的所有数据</span></span><br><span class="line"><span class="string">        全部封装给查询出来的对象</span></span><br><span class="line"><span class="string">            这个时候对象无论是点击book表的数据还是publish的数据都无需再走数据库查询了</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">        select_related括号内只能放外键字段    一对多 一对一</span></span><br><span class="line"><span class="string">            多对多也不行</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> res:</span><br><span class="line">            <span class="built_in">print</span>(i.publish.name)  <span class="comment"># 每循环一次就要走一次数据库查询</span></span><br><span class="line"></span><br><span class="line">        res = models.Book.objects.prefetch_related(<span class="string">&#x27;publish&#x27;</span>)  <span class="comment"># 子查询</span></span><br><span class="line">        <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">        prefetch_related该方法内部其实就是子查询</span></span><br><span class="line"><span class="string">            将子查询查询出来的所有结果也给你封装到对象中</span></span><br><span class="line"><span class="string">            给你的感觉好像也是一次性搞定的</span></span><br><span class="line"><span class="string">        &quot;&quot;&quot;</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> res:</span><br><span class="line">            <span class="built_in">print</span>(i.publish.name)</span><br></pre></td></tr></table></figure>

<h2 id="十七、choices参数-数据库字段设计常见"><a href="#十七、choices参数-数据库字段设计常见" class="headerlink" title="十七、choices参数(数据库字段设计常见)"></a>十七、choices参数(数据库字段设计常见)</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">用户表	</span></span><br><span class="line"><span class="string">	性别</span></span><br><span class="line"><span class="string">	学历</span></span><br><span class="line"><span class="string">	工作经验</span></span><br><span class="line"><span class="string">	是否结婚</span></span><br><span class="line"><span class="string">	是否生子</span></span><br><span class="line"><span class="string">	客户来源</span></span><br><span class="line"><span class="string">	...</span></span><br><span class="line"><span class="string">针对某个可以列举完全的可能性字段，我们应该如何存储</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">只要某个字段的可能性是可以列举完全的，那么一般情况下都会采用choices参数</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">    username = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    age = models.IntegerField()</span><br><span class="line">    <span class="comment"># 性别</span></span><br><span class="line">    gender_choices = (</span><br><span class="line">        (<span class="number">1</span>,<span class="string">&#x27;男&#x27;</span>),</span><br><span class="line">        (<span class="number">2</span>,<span class="string">&#x27;女&#x27;</span>),</span><br><span class="line">        (<span class="number">3</span>,<span class="string">&#x27;其他&#x27;</span>),</span><br><span class="line">    )</span><br><span class="line">    gender = models.IntegerField(choices=gender_choices)</span><br><span class="line">    </span><br><span class="line">    score_choices = (</span><br><span class="line">        (<span class="string">&#x27;A&#x27;</span>,<span class="string">&#x27;优秀&#x27;</span>),</span><br><span class="line">        (<span class="string">&#x27;B&#x27;</span>,<span class="string">&#x27;良好&#x27;</span>),</span><br><span class="line">        (<span class="string">&#x27;C&#x27;</span>,<span class="string">&#x27;及格&#x27;</span>),</span><br><span class="line">        (<span class="string">&#x27;D&#x27;</span>,<span class="string">&#x27;不合格&#x27;</span>),</span><br><span class="line">    )</span><br><span class="line">    <span class="comment"># 保证字段类型跟列举出来的元祖第一个数据类型一致即可</span></span><br><span class="line">    score = models.CharField(choices=score_choices,null=<span class="literal">True</span>)</span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    该gender字段存的还是数字 但是如果存的数字在上面元祖列举的范围之内</span></span><br><span class="line"><span class="string">    那么可以非常轻松的获取到数字对应的真正的内容</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">    1.gender字段存的数字不在上述元祖列举的范围内容</span></span><br><span class="line"><span class="string">    2.如果在 如何获取对应的中文信息</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    </span><br><span class="line">      </span><br><span class="line">    <span class="keyword">from</span> app01 <span class="keyword">import</span> models</span><br><span class="line">    models.User.objects.create(username=<span class="string">&#x27;jason&#x27;</span>,age=<span class="number">18</span>,gender=<span class="number">1</span>)</span><br><span class="line">    models.User.objects.create(username=<span class="string">&#x27;egon&#x27;</span>,age=<span class="number">85</span>,gender=<span class="number">2</span>)</span><br><span class="line">    models.User.objects.create(username=<span class="string">&#x27;tank&#x27;</span>,age=<span class="number">40</span>,gender=<span class="number">3</span>)</span><br><span class="line">    <span class="comment"># 存的时候 没有列举出来的数字也能存（范围还是按照字段类型决定）</span></span><br><span class="line">    models.User.objects.create(username=<span class="string">&#x27;tony&#x27;</span>,age=<span class="number">45</span>,gender=<span class="number">4</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 取</span></span><br><span class="line">    user_obj = models.User.objects.<span class="built_in">filter</span>(pk=<span class="number">1</span>).first()</span><br><span class="line">    <span class="built_in">print</span>(user_obj.gender)  <span class="comment"># 1</span></span><br><span class="line">    <span class="comment"># 只要是choices参数的字段 如果你想要获取对应信息 固定写法 get_字段名_display()</span></span><br><span class="line">    <span class="built_in">print</span>(user_obj.get_gender_display())</span><br><span class="line"></span><br><span class="line">    user_obj = models.User.objects.<span class="built_in">filter</span>(pk=<span class="number">4</span>).first()</span><br><span class="line">    <span class="comment"># 如果没有对应关系 那么字段是什么还是展示什么</span></span><br><span class="line">    <span class="built_in">print</span>(user_obj.get_gender_display())  <span class="comment"># 4</span></span><br><span class="line">    </span><br></pre></td></tr></table></figure>

<h2 id="十八、MTV与MVC模型"><a href="#十八、MTV与MVC模型" class="headerlink" title="十八、MTV与MVC模型"></a>十八、MTV与MVC模型</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># MTV:Django号称是MTV模型</span></span><br><span class="line">M:models</span><br><span class="line">T:templates</span><br><span class="line">V:views</span><br><span class="line"><span class="comment"># MVC:其实django本质也是MVC</span></span><br><span class="line">M:models</span><br><span class="line">V:views</span><br><span class="line">C:controller</span><br><span class="line">  </span><br><span class="line"><span class="comment"># vue框架:MVVM模型</span></span><br></pre></td></tr></table></figure>

<h2 id="十九、多对多表关系的三种创建方式"><a href="#十九、多对多表关系的三种创建方式" class="headerlink" title="十九、多对多表关系的三种创建方式"></a>十九、多对多表关系的三种创建方式</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 全自动:利用orm自动帮我们创建第三张关系表</span></span><br><span class="line">	<span class="class"><span class="keyword">class</span> <span class="title">Book</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">        authors = models.ManyToManyField(to=<span class="string">&#x27;Author&#x27;</span>)</span><br><span class="line">	<span class="class"><span class="keyword">class</span> <span class="title">Author</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">   		name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">	<span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">	优点:代码不需要你写 非常的方便 还支持orm提供操作第三张关系表的方法...</span></span><br><span class="line"><span class="string">	不足之处:第三张关系表的扩展性极差(没有办法额外添加字段...)</span></span><br><span class="line"><span class="string">	&quot;&quot;&quot;</span></span><br><span class="line"><span class="comment"># 纯手动</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">      	name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Author</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">  </span><br><span class="line">	<span class="class"><span class="keyword">class</span> <span class="title">Book2Author</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        book_id = models.ForeignKey(to=<span class="string">&#x27;Book&#x27;</span>)</span><br><span class="line">        author_id = models.ForeignKey(to=<span class="string">&#x27;Author&#x27;</span>)</span><br><span class="line">      <span class="string">&#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="string">      优点:第三张表完全取决于你自己进行额外的扩展</span></span><br><span class="line"><span class="string">      不足之处:需要写的代码较多，不能够再使用orm提供的简单的方法</span></span><br><span class="line"><span class="string">      不建议你用该方式</span></span><br><span class="line"><span class="string">      &#x27;&#x27;&#x27;</span></span><br><span class="line"><span class="comment"># 半自动</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">        authors = models.ManyToManyField(to=<span class="string">&#x27;Author&#x27;</span>,</span><br><span class="line">                                         through=<span class="string">&#x27;Book2Author&#x27;</span>,</span><br><span class="line">                                         through_fields=(<span class="string">&#x27;book&#x27;</span>,<span class="string">&#x27;author&#x27;</span>)</span><br><span class="line">                                         )</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Author</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">        <span class="comment"># books = models.ManyToManyField(to=&#x27;Book&#x27;,</span></span><br><span class="line">        <span class="comment">#                                  through=&#x27;Book2Author&#x27;,</span></span><br><span class="line">        <span class="comment">#                                  through_fields=(&#x27;author&#x27;,&#x27;book&#x27;)</span></span><br><span class="line">        <span class="comment">#                                  )</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book2Author</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        book = models.ForeignKey(to=<span class="string">&#x27;Book&#x27;</span>)</span><br><span class="line">        author = models.ForeignKey(to=<span class="string">&#x27;Author&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    through_fields字段先后顺序</span></span><br><span class="line"><span class="string">        判断的本质：</span></span><br><span class="line"><span class="string">            通过第三张表查询对应的表 需要用到哪个字段就把哪个字段放前面</span></span><br><span class="line"><span class="string">        你也可以简化判断</span></span><br><span class="line"><span class="string">            当前表是谁 就把对应的关联字段放前面</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    半自动:可以使用orm的正反向查询 但是没法使用add,set,remove,clear这四个方法</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 总结:你需要掌握的是全自动和半自动 为了扩展性更高 一般我们都会采用半自动(写代码要给自己留一条后路)</span></span><br></pre></td></tr></table></figure>


            </div>

            <!-- Post Comments -->
            
    <!-- 使用 DISQUS_CLICK -->
<div id="disqus-comment">
    <div id="disqus_thread"></div>

<!-- add animation -->
<style>
	.disqus_click_btn {
            line-height: 30px;
            margin: 0;
            min-width: 50px;
            padding: 0 14px;
            display: inline-block;
            font-family: "Roboto", "Helvetica", "Arial", sans-serif;
            font-size: 14px;
            font-weight: 400;
            text-transform: uppercase;
            letter-spacing: 0;
            overflow: hidden;
            will-change: box-shadow;
            transition: box-shadow .2s cubic-bezier(.4, 0, 1, 1), background-color .2s cubic-bezier(.4, 0, .2, 1), color .2s cubic-bezier(.4, 0, .2, 1);
            outline: 0;
            cursor: pointer;
            text-decoration: none;
            text-align: center;
            vertical-align: middle;
            border: 0;
            background: rgba(158, 158, 158, .2);
            box-shadow: 0 2px 2px 0 rgba(0, 0, 0, .14), 0 3px 1px -2px rgba(0, 0, 0, .2), 0 1px 5px 0 rgba(0, 0, 0, .12);
            color: #fff;
            background-color: #7EC0EE;
            text-shadow: 0
        }
</style>
	
<div class="btn_click_load" id="disqus_bt"> 
    <button class="disqus_click_btn">点击查看评论</button>
</div>

<!--
<script type="text/javascript">
$('.btn_click_load').click(function() {
    /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
    var disqus_shortname = 'http-miccall-tech'; // required: replace example with your forum shortname

    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
      var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();

    document.getElementById('disqus_bt').style.display = "none";
});
</script>
-->
<script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'https://gitee.com/AmeX/amelin-ting.git/2018/05/05/Django------%E6%95%B0%E6%8D%AE%E5%BA%93(MySQL)/';  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = 'https://gitee.com/AmeX/amelin-ting.git/2018/05/05/Django------%E6%95%B0%E6%8D%AE%E5%BA%93(MySQL)/'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };
</script>

<script type="text/javascript">
    $('.btn_click_load').click(function() {  //click to load comments
        (function() { // DON'T EDIT BELOW THIS LINE
            var d = document;
            var s = d.createElement('script');
            s.src = '//http-miccall-tech.disqus.com/embed.js';
            s.setAttribute('data-timestamp', + new Date());
            (d.head || d.body).appendChild(s);
        })();
        $('.btn_click_load').css('display','none');
    });
</script>
</div>
<style>
    #disqus-comment{
        background-color: #eee;
        padding: 2pc;
    }
</style>


        </div>
        <!-- Copyright 版权 start -->
                <div id="copyright">
            <ul>
                <li>&copy;Powered By <a target="_blank" rel="noopener" href="https://hexo.io/zh-cn/" style="border-bottom: none;">hexo</a></li>
                <li>Design: <a target="_blank" rel="noopener" href="http://miccall.tech " style="border-bottom: none;">miccall</a></li>
            </ul>
            
                <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
			
        </div>
    </div>
</body>



 	
</html>
